<?php
namespace app\acc\controller;


use app\common\logic\LiXinLogic;
use Think\Controller;
use think\Db;
use think\Page;

class Mining extends Sign
{
    public function index()
    {
        return $this->fetch();
    }

    /**
     * 我的矿机
     */
    public function my_mining()
    {
        $where['user_id'] = $this->getAccount()['id'];
        $miners = Db::name('user_miner')
                    ->alias('um')
                    ->join('__WORLD_MINER__ wm', 'um.miner_id = wm.miner_id','left')
                    ->where($where)
                    ->count();
        $this->assign('count',$miners);

        return $this->fetch();
    }

    /**
     * 我的矿机
     */
    public function ajaxMyMiner()
    {
        if (IS_POST) {
            $status = input('status');
            if (!$status) {$this->ajaxError('异常');}
            $user_id = $this->getAccount()['id'];
            if ($status == 1) {
                $miner_status = 1;
            } else {
                $miner_status = 2;
            }
            $sqlCount = 'SELECT  COUNT(*) AS tp_count FROM `tp_user_miner` `um` LEFT JOIN `tp_world_miner` `wm` ON `um`.`miner_id`=`wm`.`miner_id` WHERE `user_id` = '.$user_id;
            $sqlCount .= '  AND um.status = '.$miner_status;
            $sqlCount .= ' LIMIT 1 ';
            $count = Db::query($sqlCount);

            $Page = new Page($count[0]['tp_count'],7);

            $sqlQuery = 'SELECT  * FROM `tp_user_miner` `um` LEFT JOIN `tp_world_miner` `wm` ON `um`.`miner_id`=`wm`.`miner_id` WHERE `user_id` = '.$user_id;
            $sqlQuery .= '  AND um.status = '.$miner_status;
            $sqlQuery .= ' order by id desc LIMIT '.$Page->firstRow.','.$Page->listRows;
            $miners = Db::query($sqlQuery);
            /*foreach ($miners as $k=>$v){
                $start_time = (time() - $v['start_time']) / 3600;
                $miners[$k]['start_times'] = round($start_time,2);
            }*/

            $this->assign('list',$miners);
            $this->assign('status',$status);
            $this->assign('time',time());
            return $this->fetch();
        }
    }

    //矿机详情
    public function minerDetail()
    {
        $miner_id = input('id');
        $where['user_id'] = $this->getAccount()['id'];
        $where['id'] = $miner_id;

        $miner = Db::name('user_miner')
                        ->alias('um')
                        ->join('__WORLD_MINER__ wm', 'um.miner_id = wm.miner_id','left')
                        ->where($where)->find();
        if (!$miner) {
            $this->error('无矿机');
        }
        $status = 1;
        if ($miner['kj_token'] <= 0 ) {
            $status = 2;
        }
        $start_time = (time() - $miner['start_time']) / 3600;
        $miner['start_times'] = round($start_time,2);
        $this->assign('miner',$miner);
        $this->assign('status',$status);
        return $this->fetch();
    }

    //领取收益
    public function profit()
    {
        if (IS_POST) {
            $id = input('post.id');
            $uid =  $this->getAccount()['id'];
            $miner = Db::name('user_miner')
                        ->alias('um')
                        ->join('__WORLD_MINER__ wm', 'wm.miner_id = um.miner_id', 'left')
                        ->where(['user_id' => $uid,'id' =>$id])
                        ->find();
            /*if ((time() - $miner['receive_time']) < 86400) {
                exit(json_encode(['code' => -1, 'msg' => "未可领取"]));
            }
            $receive = date("Y-m-d H:i:s",time());
            $tomorrow = date("Y-m-d",time()) .' 23:59:59';
            if ($receive < $tomorrow) {
                exit(json_encode(['code' => -1, 'msg' => "未到可领取时间"]));
            }

            if (date("Y-m-d",$miner['receive_time']) == date("Y-m-d",time())) {
                exit(json_encode(['code' => -1, 'msg' => "您已领取过！"]));
            }*/

            $logic = new LiXinLogic();
            $result = $logic->porfit($miner);
            if ($result) {
                exit(json_encode(['code' => 1, 'msg' => "领取成功"]));
            }
            exit(json_encode(['code' => -1, 'msg' => "领取失败"]));
        }
    }

    /*public function profit()
    {
        if (IS_POST) {
            $id = input('post.id');
            $uid =  $this->getAccount()['id'];
            $miner = Db::name('user_miner')
                ->alias('um')
                ->join('__WORLD_MINER__ wm', 'wm.miner_id = um.miner_id', 'left')
                ->where(['user_id' => $uid,'id' =>$id])
                ->find();
            if ((time() - $miner['receive_time']) < 86400) {
                exit(json_encode(['code' => -1, 'msg' => "未可领取"]));
            }
            if ($miner['all_profit'] == $miner['receive']) {
                exit(json_encode(['code' => -1, 'msg' => "当前矿机无收益"]));
            }
            // if ($miner['invalid_time'] < time()) {
            //     exit(json_encode(['code' => -1, 'msg' => "矿机已失效"]));
            // }
            $logic = new \app\common\logic\LiXinLogic();
            $result = $logic->porfit($miner);
            if ($result) {
                exit(json_encode(['code' => 1, 'msg' => "领取成功"]));
            }
            exit(json_encode(['code' => -1, 'msg' => "领取失败"]));
        }
    }*/

    //一键开启
    public function allStart()
    {
        $uid =  $this->getAccount()['id'];
        $sqlCount = 'SELECT  * FROM `tp_user_miner` WHERE `user_id` = '.$uid;
        $sqlCount .= ' AND is_start = 0 AND status = 1';
        $miners = Db::query($sqlCount);

        foreach ($miners as $key => $va) {
            $data = [
                'is_start' => 1,
                'start_time' => time(),
                'start_days' => $miners['start_days'] + 1
            ];
            Db::name('user_miner')->where(['id' => $va['id']])->update($data);
            //判断是否已收益矿机，没有自动收益
            if (date("Y-m-d",$va['receive_time']) < date("Y-m-d",time())){
                $this->profit($miners);
            }
        }
        exit(json_encode(['code' => 1, 'msg' => "操作成功"]));

    }

    //一键领取
    public function allProfit()
    {
        $uid =  $this->getAccount()['id'];
        // 统计可领取的矿机数量,最后一次领取时间是否小于可领取时间
        $count = Db::name('user_miner')
            ->alias('um')
            ->where([
                'um.user_id' => $uid,
                'um.is_start' => 1,
                'um.status' => 1,
                'um.receive_time' => ['LT', time()-86400]
            ])
            ->count();

        if ($count != 0) {
            exit(json_encode(['code' => -1, 'msg' => "没有可领取矿机"]));
        }

        $sqlCount = 'SELECT  * FROM `tp_user_miner` `um` LEFT JOIN `tp_world_miner` `wm` ON `um`.`miner_id`=`wm`.`miner_id` WHERE `um`.`user_id` = '.$uid;
        $sqlCount .= ' AND um.is_start = 1 AND um.status = 1 AND `um`.`receive_time` > '. (time()-86400);
        $miners = Db::query($sqlCount);

        if (!empty($miners)){
            $logic = new LiXinLogic();
            foreach ($miners as $key => $va) {
                $result = $logic->porfit($va);
            }
        }else{
            exit(json_encode(['code' => -1, 'msg' => "未可领取"]));
        }

        exit(json_encode(['code' => 1, 'msg' => "操作成功"]));

    }

    //预存token
    public function preToken(){
        $uid =  $this->getAccount()['id'];
        if (IS_POST){
            $res_all_token = Db::name('all_token')->find();
            $number= input('tqNumber');
            $paypassword = input('paypassword');
            //查询用户信息
            $info = Db::name('member')->where(['id' => $uid])->find();
            $miner = Db::name('user_miner')->where('user_id', $uid)->find();
            $worldMiner = Db::name('world_miner')->where('miner_id', $miner['miner_id'])->find();
            if ($number == 0 || empty($number)){
                $this->ajaxError('请输入预存数量！');
            }
            if ($info['miner'] <= 0){
                $this->ajaxError('可使用金额不足！');
            }
            if ($info['miner'] < $number){
                $this->ajaxError('预存数量不得大于可用余额数量！');
            }
            if ($miner['miner_price'] != $number){
                $this->ajaxError('预存数量必须等于该矿机投资金额！');
            }
            if ($info['paypassword'] != md5($paypassword)){
                $this->ajaxError('二级密码错误！');
            }
            //存入用户总token
            /*$userData = [
                'kj_all_token' => $info['kj_all_token'] + $number,
                'miner' => $info['miner'] - $number
            ];*/
            $userData = [
                'kj_all_token' => $info['kj_all_token'],
                'miner' => $info['miner'] - $number
            ];
            if ($res_all_token['total'] - ($number * $worldMiner['multiple']) <= 0){
                exit(json_encode(['code' => -1, 'msg' =>'矿机已禁止购买']));
            }
            $res_pre_token = Db::name('member')->where('id', $uid)->update($userData);
            $kj_pre_token = ($miner['kj_pre_token'] + ($number * $worldMiner['multiple']));
            $res_user_miner = Db::name('user_miner')->where('id', $miner['id'])->update(['kj_pre_token'=>$kj_pre_token,'status' => 1]);
            $logRes = minerlog($miner['id'], $uid, -$number, 9, $info['miner'], $userData['miner'], '预存token扣除');
            if ($res_pre_token && $res_user_miner && $logRes){
                $shengYu = $res_all_token['total'] - $worldMiner['multiple'] * $number;
                Db::name('all_token')->where(['id' => $res_all_token['id']])->update(['total' => $shengYu]);
                $tokenLogData = [
                    'userId' => $uid,
                    'createTime' => date("Y-m-d H:i:s",time()),
                    'miner_id' => $miner['miner_id'],
                    'kj_token' => $worldMiner['multiple'] * $number,
                    'desc' => '购买矿机扣除'
                ];
                Db::name('all_token_log')->insert($tokenLogData);
                $this->countUserParentReceive($info['parentId'],$kj_pre_token);
                $this->ajaxSuccess('预存成功！');
            }else{
                $this->ajaxError('提取失败！');
            }

        }
        $id = I('id');
        $user = Db::name('member')->where('id', $uid)->field(['id','miner','kj_all_token'])->find();
        $miner = Db::name('user_miner')->where('id', $id)->find();
        $worldMiner = Db::name('world_miner')->where('miner_id', $miner['miner_id'])->find();
        $this->assign('worldMiner', $worldMiner);
        $this->assign('miner', $miner);
        $this->assign('user', $user);
        return $this->fetch();
    }

    /**
     * 计算直推用户收益
     * parentId：用户直推id
     * miner_id：矿机id
     * */
    public function countUserParentReceive($parentId, $miner_price){
        //查询直推用户信息
        $userParent =  Db::name('member')->where('id', $parentId)->field('id,account,miner,kj_all_token,all_receive,parentId')->find();
        if (!empty($userParent)){
            //查询直推用户购买矿机总金额
            $userMiner =  Db::name('user_miner')->where(['user_id' => $userParent['id'],'status' => 1,'type' => 1])->find();
            //如上级用户未购买矿机，则不增加收益
            if (!empty($userMiner)){
                if ($userMiner['miner_price'] >= $miner_price){
                    //上级用户购买总金额大于下级用户购买金额，选取下级用户支付金额 * 0.1作为收益
                    $receive = $miner_price * 0.1;
                }else{
                    //非同类矿机
                    $receive = $userMiner['miner_price'] * 0.1;
                }
                $afterToken = $userParent['kj_all_token'] - $receive;
                if ($afterToken <= 0){
                    //如果token不够扣的，则直接返回
                    return  true;
                }
                //增加用户总收益
                $userData['miner'] = $userParent['miner'] + $receive;
                $userData['all_receive'] = $userParent['all_receive'] + $receive;
                //减少用户总token
                $userData['kj_all_token'] = $afterToken;
                $result = Db::name('member')->where('id', $userParent['id'])->save($userData);
                //减少矿机token
                $res_user_miner = Db::name('user_miner')->where('user_id', $userParent['id'])->save(['kj_token'=>($userMiner['kj_token']-$receive)]);
                if ($result && $res_user_miner){
                    //添加操作记录
                    $operate = '直推用户获取收益，直推用户id： '.$userParent['id'].'增加收益：'.$receive;
                    minerlog(777, $userParent['id'], +$receive, 7, $userParent['miner'], $userData['miner'], '直推奖');
                    $this->addOperateLog($userParent['id'], $userParent['account'], $operate, $userParent['miner'], $userData['miner']);
                    $this->countThree($userParent['parentId'],$receive);
                    return true;
                }else{
                    return false;
                }
            }
            return true;
        }
        return true;
    }
    /*public function countUserParentReceive($parentId, $miner_price){
        //查询直推用户信息
        $userParent =  Db::name('member')->where('id', $parentId)->field('id,account,miner,kj_all_token,all_receive')->find();
        if (!empty($userParent)){
            //查询直推用户购买矿机总金额
            $parentBuyPeice = Db::name('user_miner')->where(['user_id' => $userParent['id'],'status' => 1,'type' => 1])->sum('miner_price');
            //如上级用户未购买矿机，则不增加收益
            if ($parentBuyPeice != 0){
                if ($parentBuyPeice >= $miner_price){
                    //上级用户购买总金额大于下级用户购买金额，选取下级用户支付金额 * 0.1作为收益
                    $receive = $miner_price * 0.1;
                }else{
                    //非同类矿机
                    $receive = $parentBuyPeice * 0.1;
                }
                //增加用户总收益
                $userData['miner'] = $userParent['miner'] + $receive;
                $userData['all_receive'] = $userParent['all_receive'] + $receive;
                //减少用户总token
                $userData['kj_all_token'] = $userParent['kj_all_token'] - $receive;
                $result = Db::name('member')->where('id', $userParent['id'])->save($userData);
                if ($result){
                    //添加操作记录
                    $operate = '直推用户获取收益，直推用户id： '.$userParent['id'].'增加收益：'.$receive;
                    minerlog(777, $userParent['id'], +$receive, 7, $userParent['miner'], $userData['miner'], '预存-直推奖');
                    $this->addOperateLog($userParent['id'], $userParent['account'], $operate, $userParent['miner'], $userData['miner']);
                    $this->countThree($userParent['parentId'],$receive);
                    return true;
                }else{
                    return false;
                }
            }
            return true;
        }
        return true;
    }*/

    /**
     * 计算上级上直推收益，30%
     * */
    public function countThree($parentId, $profit){
        $userParent =  Db::name('member')->where('id', $parentId)->field('id,account,miner,kj_all_token,all_receive,parentId')->find();
        if (!empty($userParent)){
            $profit = $profit * 0.3;
            //增加用户总收益
            $userData['miner'] = $userParent['miner'] + $profit;
            $userData['all_receive'] = $userParent['all_receive'] + $profit;
            //减少用户总token
            $userData['kj_all_token'] = $userParent['kj_all_token'] - $profit;
            if ($userData['kj_all_token'] <= 0){
                return true;
            }
            $result = Db::name('member')->where('id', $userParent['id'])->save($userData);
            $userMiner =  Db::name('user_miner')->where(['user_id' => $userParent['id'],'status' => 1,'type' => 1])->find();
            $res_user_miner = Db::name('user_miner')->where('user_id', $userParent['id'])->save(['kj_token'=>($userMiner['kj_token']-$profit)]);
            minerlog(777, $userParent['id'], +$profit, 6, $userParent['miner'], $userData['miner'], '管理奖');
            if ($result && $res_user_miner){
                $this->countThree($userParent['parentId'], $profit);
            }else{
                Log::info('用户购买30%，直推奖添加失败！');
            }
        }else{
            return true;
        }
    }
    /*public function countThree($parentId, $profit){
        $userParent =  Db::name('member')->where('id', $parentId)->field('id,account,miner,kj_all_token,all_receive,parentId')->find();
        if (!empty($userParent)){
            $profit = $profit * 0.3;
            //增加用户总收益
            $userData['miner'] = $userParent['miner'] + $profit;
            $userData['all_receive'] = $userParent['all_receive'] + $profit;
            //减少用户总token
            $userData['kj_all_token'] = $userParent['kj_all_token'] - $profit;
            $result = Db::name('member')->where('id', $userParent['id'])->save($userData);
            minerlog(777, $userParent['id'], +$profit, 6, $userParent['miner'], $userData['miner'], '管理奖');
            if ($result){
                $this->countThree($userParent['parentId'], $profit);
            }else{
                Log::info('用户购买30%，直推奖添加失败！');
            }
        }else{
            return true;
        }
    }*/

    //一键领取 ---- 原先版 ---2020.08.02
    /*public function allProfit()
    {
        $uid =  $this->getAccount()['id'];
        // 统计未失效的矿机数量

        $count = Db::name('user_miner')
                    ->alias('um')
                    ->where([
                        'um.user_id' => $uid,
                        'um.invalid_time'=>['Gt', time()],
                        'um.receive_time' => ['GT', time()-86400]
                        ])
                    ->count();

        $count2 = Db::name('user_miner')
                    ->alias('um')
                    ->where([
                        'um.user_id' => $uid,
                        'um.invalid_time'=>['LT', time()],
                        'um.all_profit' => ['NEQ', 'um.receive'],
                        'um.receive_time' => ['GT', time()-86400],
                        ])
                    ->count();

        if ($count || $count2) {
            exit(json_encode(['code' => -1, 'msg' => "未可领取"]));
        }

        $sqlCount = 'SELECT  * FROM `tp_user_miner` `um` LEFT JOIN `tp_world_miner` `wm` ON `um`.`miner_id`=`wm`.`miner_id` WHERE `user_id` = '.$uid;
        $sqlCount .= ' AND ( ( `um`.`invalid_time` > '.time().' AND `um`.`receive_time` < '. (time()-86400).' ) ';
        $sqlCount .= ' OR ( `um`.`all_profit` <> `um`.`receive` AND `um`.`invalid_time` < '.time().' )  ) ';
        $miners = Db::query($sqlCount);

        $logic = new \app\common\logic\LiXinLogic();
        $profit = 0;
        foreach ($miners as $key => $va) {
            $result = $logic->porfit($va);
        }
        exit(json_encode(['code' => 1, 'msg' => "操作成功"]));

    }*/

    /**
     * 兑换管理
     */
    public function exchange()
    {
        $uid =  $this->getAccount()['id'];
        $user = Db::name('member')->field('id,paypassword,balance,miner')->find($uid);
        $multiple = Db::name('world_system')->where(['inc_type' => 'basic', 'name' => 'balance_wallet'])->value('value');
        if (IS_POST) {
            $balance = input('post.balance');
            $paypwd = input('post.paypwd');
            if ($user['paypassword'] != md5($paypwd)) {
                exit(json_encode(['code' => -1, 'msg' => "密码错误"]));
            }
            if ($user['balance'] <$balance) {
                exit(json_encode(['code' => -1, 'msg' => "兑换资产不足"]));
            }
            Db::startTrans();

            $after_balance = $user['balance'] - $balance;
            $miner = $balance*$multiple;
            $after_miner = $user['miner'] + $miner;

            $exchangeData = [
                'user_id' => $uid,
                'multiple' => $multiple,
                'number' => $balance,
                'after_balance' => $after_balance,
                'after_miner' => $after_miner,
                'add_time' => time()
            ];
            $exchangeRes = Db::name('balance_miner')->insertGetId($exchangeData);
            // 兑换
            $userData = ['balance' => $after_balance, 'miner' => $after_miner];
            // 钱包记录
            $logRes = balanceLog($uid, $exchangeRes ,(-1)*$balance,'兑换矿池钱包',6,0);
            $logRes2 = minerlog($exchangeRes, $uid, $miner, 3, $user['miner'],$after_miner, '兑换余额获得');
            $userRes = Db::name('member')->where(['id' => $uid])->update($userData);
            if ($exchangeRes && $logRes && $logRes2 && $userRes) {
                Db::commit();
                exit(json_encode(['code' => 1, 'msg' => "兑换成功"]));
            }
            Db::rollback();
            exit(json_encode(['code' => -1, 'msg' => "兑换失败"]));
        }
        $this->assign('user', $user);
        $this->assign('multiple', $multiple);
        return $this->fetch();
        return $this->fetch();
    }
    /**
     * 矿池资产
     */
    public function orepool_assets()
    {
        $uid =  $this->getAccount()['id'];
        $user = Db::name('member')->field('id,paypassword,miner,miner_pool')->find($uid);
        $multiple = Db::name('world_system')->where(['inc_type' => 'miner_basic', 'name' => 'multiple'])->value('value');
        if (IS_POST) {
            $miner = input('post.miner');
            $paypwd = input('post.paypwd');
            if ($user['paypassword'] != md5($paypwd)) {
                exit(json_encode(['code' => -1, 'msg' => "密码错误"]));
            }
            if ($user['miner'] <$miner) {
                exit(json_encode(['code' => -1, 'msg' => "兑换资产不足"]));
            }
            Db::startTrans();

            $after_miner = $user['miner'] - $miner;
            $miner_pool = $miner*$multiple;
            $after_miner_pool = $user['miner_pool'] + $miner_pool;

            $exchangeData = [
                'user_id' => $uid,
                'multiple' => $multiple,
                'number' => $miner,
                'after_miner' => $after_miner,
                'after_miner_pool' => $after_miner_pool
            ];
            $exchangeRes = Db::name('miner_exchange')->insertGetId($exchangeData);
            // 兑换
            $userData = ['miner' => $after_miner, 'miner_pool' => $after_miner_pool];
            // 钱包记录
            $logRes = minerlog($exchangeRes, $uid, -$miner, 3, $user['miner'],$after_miner, '兑换扣除');
            $logRes2 = miner_poollog($exchangeRes, $uid, $miner_pool, 4, $user['miner_pool'],$after_miner_pool, '兑换获得');
            $userRes = Db::name('member')->where(['id' => $uid])->update($userData);
            if ($exchangeRes && $logRes && $logRes2 && $userRes) {
                Db::commit();
                exit(json_encode(['code' => 1, 'msg' => "兑换成功"]));
            }
            Db::rollback();
            exit(json_encode(['code' => -1, 'msg' => "兑换失败"]));
        }
        $this->assign('user', $user);
        $this->assign('multiple', $multiple);
        return $this->fetch();
    }


    public function release()
    {
        if (IS_POST) {
            $uid =  $this->getAccount()['id'];
            $user = Db::name('member')->field('id,miner_pool,balance')->find($uid);
            // 获取上次释放时间
            $logInfo = Db::name('miner_poollog')->where(['userId' => $uid, 'type' => 7])->order('id desc')->find();
            if ($logInfo) { //有记录存在 判断是否满足时间 无记录存在 首次释放
                $time = strtotime($logInfo['createTime']);
                $timeConfig = Db::name('world_system')->where(['inc_type' => 'miner_basic', 'name' => 'release_time'])->value('value');
                $timeConfig *= 60;
                if ($time+$timeConfig >time()) {
                    $time2 = date('Y-m-d H:i:s', $time+$timeConfig);
                    exit(json_encode(['code' => -1, 'msg' => "释放失败，请在".$time2.'后释放']));
                }
            }

            $config = Db::name('world_system')->where(['inc_type' => 'miner_basic', 'name' => 'relase_size'])->value('value');
            Db::startTrans();
            // 本次释放值
            $relaseSize = $user['miner_pool'] * $config;
            $afterMinerPool = $user['miner_pool'] - $relaseSize;
            $afterBalance = $user['balance'] + $relaseSize;

            $logRes = miner_poollog(0, $uid, -$relaseSize, 7, $user['miner_pool'],$afterMinerPool, '释放扣除');

            $account_log = array(
                'userId' => $uid,
                'num' => $relaseSize,
                'reflectId' => $logRes,
                'type' => 8,
                'before' => $user['balance'],
                'after' => $afterBalance,
                'createTime' => date('Y-m-d H:i:s',time()),
                'updateTime' => date('Y-m-d H:i:s',time()),
                'desc' => '释放获得'
            );

            $logRes2 = Db::name('balancelog')->add($account_log);

            // $logRes2 = balancelog($logRes, $uid, $relaseSize, 8, $user['balance'],$afterBalance, '释放获得');
            $userData = ['balance' => $afterBalance, 'miner_pool' => $afterMinerPool];
            $userRes = Db::name('member')->where(['id' => $uid])->update($userData);

            if ($logRes && $logRes2 && $userRes) {
                Db::commit();
                exit(json_encode(['code' => 1, 'msg' => "释放成功"]));
            }
            Db::rollback();
            exit(json_encode(['code' => -1, 'msg' => "释放失败"]));
        }

    }

    /**
     * 交易规则
     */
    public function rule()
    {
        $info = Db::name('article')->find(46);
        $this->assign('info',$info);
        return $this->fetch();
    }

}
